<template>
    <view>
        <!-- 自定义导航栏 -->
        <myNavigation ref="navBar"></myNavigation>
        <view class="userInfo">
            <view class="profile_photo" @tap.stop="uploadPhoto">
                <image :src="userBaseInfo.photoUrl" mode="aspectFill" />
                <view class="cover">上传头像</view>
            </view>
            <view class="user_name">
                <view class="title">昵称</view>
                <input type="text" v-model="userBaseInfo.userName" @input="hideTip" @blur="validUserName">
                <view class="user_name_tip"
                    :class="[{hide:isHideTip},{error:!isValidUserName},{success:(isValidUserName && userBaseInfo.userName !== userName_old)}]">
                    {{userNameTip}}</view>
            </view>

            <view class="submit_setting" @tap.stop="modifyUserInfo">保&nbsp;存&nbsp;修&nbsp;改</view>
        </view>


    </view>
</template>

<script setup>
    import { ref, onMounted, inject, reactive } from 'vue';
    import "./settingUserInfo.scss";
    import Taro, { useRouter, useDidShow } from "@tarojs/taro";
    import { AtInput, AtButton } from 'taro-ui-vue3'
    import myNavigation from "../../../components/myNavigation.vue";
    // 注入配置
    const config = inject('config');
    const baseUrl = config.baseUrl; // 从全局配置中读取 baseUrl


    // 导航栏信息
    const navBar = ref(null);
    const navigationHome = () => {
        Taro.switchTab({
            url: '../../../pages/index/index',
        });
    };
    const setNavBar = () => {
        if (navBar.value) {
            navBar.value.navigationHome = navigationHome;
            navBar.value.navigationTitle = `编辑个人资料`;
        }
    }

    // 上传头像
    const uploadPhoto = async () => {
        try {
            const res = await Taro.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
            });

            // 返回选定照片的本地文件路径列表 tempFilePaths
            const tempFilePaths = res.tempFilePaths;
            showLoading("头像上传中");
            const uploadRes = await Taro.uploadFile({
                url: 'https://www.helloimg.com/api/v1/upload',
                filePath: tempFilePaths[0],
                name: 'file',
                formData: {
                    'album_id': 983,
                },

                header: {
                    'Content-Type': 'multipart/form-data',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer 552|NZWxIBAYUIFtppMZOt1geLgbNUuTzXZ7yvyNKwg5',
                },
            });

            const imgData = JSON.parse(uploadRes.data);
            userBaseInfo.value.photoUrl = imgData.data.links.url;
        } catch (error) {
            console.error("Error uploading photo", error);
        } finally {
            // 隐藏加载中提示
            hideLoading();
        }
    };



    const userBaseInfo = ref({
        userId: '',
        userName: "",
        photoUrl: ""
    })

    const isValidUserName = ref(false);
    const userNameTip = ref("")
    const isHideTip = ref(true)
    const hideTip = () => {
        isHideTip.value = true;
    }

    // 显示加载中提示
    function showLoading(title) {
        Taro.showLoading({
            title: `${title}`,
            mask: true,
        })
    };
    // 隐藏加载中提示
    function hideLoading() {
        Taro.hideLoading();
    };

    // 判断昵称是否存在
    const validUserName = async () => {
        isHideTip.value = false;
        // 显示加载中提示
        showLoading();
        try {
            const res = await Taro.request({
                url: `${baseUrl}/user/isExistUserName?userName=${userBaseInfo.value.userName}`,
            });
            if (res.data.message === "success" || userName_old.value === userBaseInfo.value.userName) {
                isValidUserName.value = true;
                userNameTip.value = res.data.data;
            } else {
                isValidUserName.value = false;
                userNameTip.value = res.data.data;
            }
        } catch (error) {
            console.error("Request failed", error);
            isValidUserName.value = false;
            userNameTip.value = "请求失败";
        } finally {
            hideLoading();
        }
    };

    // 修改信息
    const modifyUserInfo = async () => {
        await validUserName();
        if (!isValidUserName.value) {
            Taro.showToast({
                title: `该昵称已被注册`,
                icon: 'error',
                mask: true,
                duration: 2000
            });
            return
        };
        console.log(userBaseInfo.value);
        Taro.request({
            url: `${baseUrl}/user/modifyUser`,
            method: 'PUT',
            data: userBaseInfo.value,
            success: function (res) {
                if (res.data.message === "success") {
                    showSuccess(res.data.data);
                } else {
                    showError(res.data.data)
                }
            }
        });
    };

    // 函数：登录成功后跳转用户界面：
    function showSuccess(msg) {
        const curTime = ref(3);
        Taro.showToast({
            title: `${msg}`,
            icon: 'success',
            mask: true,
            duration: 1000,
            complete: () => {
                const intervalId = setInterval(() => {
                    curTime.value -= 1;
                    if (curTime.value > 0) {
                        Taro.showToast({
                            title: `${msg},${curTime.value}s后跳返回用户界面`,
                            icon: 'none',
                            mask: true,
                            duration: 1000 // 每次显示1秒
                        });
                    } else {
                        clearInterval(intervalId); // 清除定时器
                        Taro.switchTab({
                            url: '../../../pages/my/my',
                        });
                    }
                }, 1000);
            }
        });
    }
    // 函数:失败显示
    function showError(msg) {
        Taro.showToast({
            title: `${msg}`,
            icon: 'error',
            duration: 2000, // 持续时间为2s
        });
    }


    // 用于存放用户之前的昵称
    const userName_old = ref();
    function getUserBaseInfo() {

        Taro.request({
            url: `${baseUrl}/user/getUserBaseInfo?userId=${curUserId.value}`,
            success: (res) => {
                userBaseInfo.value = res.data.data;
                userName_old.value = userBaseInfo.value.userName;

            }
        })

    }
    // 存放当前登录用户
    const curUserId = ref('');
    Taro.useDidShow(() => {
        curUserId.value = Taro.getStorageSync('userId')
        getUserBaseInfo();

    })
    onMounted(() => {
        setNavBar();
    });
</script>

<style lang="scss" scoped></style>